package com.lin.mr.maizilaundry.fragmentmain;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lin.mr.maizilaundry.R;
import com.lin.mr.maizilaundry.activity.ClothActivity;
import com.lin.mr.maizilaundry.activity.ServeActivity;
import com.lin.mr.maizilaundry.entity.Laundry;
import com.lin.mr.maizilaundry.myapplication.MyApplication;
import com.lin.mr.maizilaundry.utils.CountEvent;
import com.lin.mr.maizilaundry.utils.TimeUtils;
import com.lin.mr.maizilaundry.utils.VolleyUtils;
import com.lin.mr.maizilaundry.utils.WashInfoJean;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 *
 */
public class FragmentHome extends Fragment implements View.OnClickListener {
    private PopupWindow popupWindow;
    private ImageView fragment_home_bag;//袋洗
    private ImageView fragment_wash_peace;
    private ImageView fragment_service_home;

    private ImageButton btn_plus, btn_minus;
    private TextView tv_sum, pop_bag_text, pop_bag_price;
    private Button btn_sure;

//    private PowerManager powerManager;
//    private PowerManager.WakeLock pWakeLock;

    private static final String TAG = "AutoPlayAdvertisement";

    private Laundry laundry;

    int sum = 1;
    private ViewPager fr_viewPager;
    int[] imageResId;//viewpage广告图片id
    private ArrayList<ImageView> imageViewList;
    private LinearLayout ll_dot_container;
    private ArrayList<View> dotViews;
    boolean isSliding = false;
    private final String URL = "http://cloud.bmob.cn/d9f6840be6bb07cf/wash_page?clive=bagpicture";
    private List<WashInfoJean.WashInfoBean> washList;
    private String currentTime;//用户下单时的时间
    private AdvImage advImage;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_home, container, false);
        fragment_home_bag = (ImageView) view.findViewById(R.id.fragment_home_bag);

        //件洗
        fragment_wash_peace = (ImageView) view.findViewById(R.id.fragment_wash_peace);
        fragment_wash_peace.setOnClickListener(this);
        //服务范围
        fragment_service_home = (ImageView) view.findViewById(R.id.fragment_service_home);
        fragment_service_home.setOnClickListener(this);

        fr_viewPager = (ViewPager) view.findViewById(R.id.fr_viewpager);
        ll_dot_container = (LinearLayout) view.findViewById(R.id.ll_dot_container);
        //设置屏幕长亮
//        powerManager = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
//        powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);

        initView();
        initPopupWindow();



        //开启广告轮播的线程
        advImage = new AdvImage();
        advImage.start();

//        new Thread() {
//            @Override
//            public void run() {
//                super.run();
//                isSliding = true;
//                while (isSliding) {
//                    try {
//                        Thread.sleep(3000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
////                    使用runOnUiThread可以在主线程更新UI
////                    由于主线程在Activity中，所以要用getActivity()调用
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            //跳转到下一个页卡
//                            fr_viewPager.setCurrentItem(fr_viewPager.getCurrentItem()+1);
//
//                        }
//                    });
//
//                }
//            }
//        }.start();

        fragment_home_bag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VolleyUtils.requestByGet(URL, "FragmentHome", new VolleyUtils.CallBack() {
                    @Override
                    public void returnData(Object result) {
                        if (result != null) {
                            Gson gson = new Gson();
                            WashInfoJean washInfoJean = gson.fromJson((String) result, WashInfoJean.class);
                            washList = new ArrayList<WashInfoJean.WashInfoBean>();
                            washList = washInfoJean.getWashInfo();
                        } else {
                            Toast.makeText(getContext(), "请检查网络！", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
//                    initPopupWindow();
                    popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);//这里的view是父控件FragmentHome
                    tv_sum.setText("1");
                }
            }
        });

        return view;
    }


    //广告轮播的线程
    class AdvImage extends Thread{
        @Override
        public void run() {
            super.run();
            isSliding = true;
            while (isSliding) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                    使用runOnUiThread可以在主线程更新UI
//                    由于主线程在Activity中，所以要用getActivity()调用
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //跳转到下一个页卡
                        fr_viewPager.setCurrentItem(fr_viewPager.getCurrentItem()+1);

                    }
                });

            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //取消广告轮播
        isSliding = false;
        advImage.interrupt();
    }

    @Override
    public void onPause() {
        super.onPause();
        //fragment失去焦点时关闭广告轮播
        isSliding = true;
        //释放屏幕长亮
//        pWakeLock.release();

    }

    //广告轮播
    private void initView() {
        imageResId = new int[]{R.drawable.ad1, R.drawable.ad2, R.drawable.ad3,
                R.drawable.ad4, R.drawable.ad5};

        imageViewList = new ArrayList<>();
        dotViews = new ArrayList<>();
        ImageView imageView;
        View dotView;
        LinearLayout.LayoutParams layoutParams;
        int count = imageResId.length;
        for (int i = 0; i < count; i++) {
            imageView = new ImageView(MyApplication.getContext());
            imageView.setBackgroundResource(imageResId[i]);
            imageViewList.add(imageView);

            dotView = new View(MyApplication.getContext());
            dotView.setBackgroundResource(R.drawable.selector_bg_point);
            layoutParams = new LinearLayout.LayoutParams(18, 18);
            if (i != 0) {
                layoutParams.leftMargin = 20;//设置点与点之间的间距，第一个点除外
            }
            dotView.setEnabled(false);
            ll_dot_container.addView(dotView, layoutParams);
        }
        ll_dot_container.getChildAt(0).setEnabled(true);

        fr_viewPager.setAdapter(new MyAdapter());
        fr_viewPager.setCurrentItem(imageViewList.size() * 10000);//使广告页卡能向左侧滑动


        fr_viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int newPosition = position % imageViewList.size();
                for (int i = 0; i < ll_dot_container.getChildCount(); i++) {
                    View childView = ll_dot_container.getChildAt(i);
                    childView.setEnabled(newPosition == i);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    class MyAdapter extends PagerAdapter {
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            int newPosition = position % imageViewList.size();
            ImageView imageView = imageViewList.get(newPosition);
            //把View对象添加到父容器container中
            container.addView(imageView);
            return imageView;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_wash_peace:
                startActivity(new Intent(getActivity(), ClothActivity.class));
                break;
            case R.id.fragment_service_home:
                startActivity(new Intent(getActivity(), ServeActivity.class));
                break;
            case R.id.pop_bag_minus:
                String amount_minus = (String) tv_sum.getText();
                sum = Integer.parseInt(amount_minus);
                if (sum == 1) {
                    return;
                } else {
                    sum--;
                    tv_sum.setText(sum + "");
                }
                break;
            case R.id.pop_bag_plus:
                String amount_plus = (String) tv_sum.getText();
                sum = Integer.parseInt(amount_plus);
                sum++;
                tv_sum.setText(sum + "");
                break;
            case R.id.btn_pop_sure:
                if (popupWindow != null && popupWindow.isShowing()) {
                    Boolean isRepeated = isRepeatedData();
                    String bag_text = (String) pop_bag_text.getText();
                    if (isRepeated) {
                        //判断用户之前是否已经将相同的衣物加入洗衣篮
                        for (int i = 0; i < MyApplication.laundries.size(); i++) {
                            laundry = MyApplication.laundries.get(i);
                            if (bag_text.equals(laundry.getPictureName())) {
                                String string1 = laundry.getAmount();
                                int amount1 = Integer.parseInt(string1);
                                String string2 = (String) tv_sum.getText();
                                int amount2 = Integer.parseInt(string2);
                                laundry.setAmount(amount1 + amount2 + "");
                                MyApplication.laundries.add(laundry);
                            }

                        }
                    } else {
                        //如果用户之前没有选择该衣物，则获取该衣物的数据并添加到集合中
                        if (laundry == null) {
                            laundry = new Laundry();
                        }
                        laundry.setPicture(washList.get(0).getWashHead());
                        laundry.setAmount((String) tv_sum.getText());
                        laundry.setPictureName((String) pop_bag_text.getText());
                        laundry.setValue((String) pop_bag_price.getText());
                        //获取下单时的时间
                        currentTime = TimeUtils.getTime(System.currentTimeMillis());
                        laundry.setTime(currentTime);
                        MyApplication.laundries.add(laundry);
                        EventBus.getDefault().post(new CountEvent(4));
                        Toast.makeText(getActivity(), "已加入洗衣篮(∩_∩)", Toast.LENGTH_SHORT).show();
                        //在没有连接网络的时候laundry为null，故加个if判断
                        if (laundry != null) {

                        } else {
                            Toast.makeText(MyApplication.getContext(), "请先连接网络！", Toast.LENGTH_SHORT).show();
                        }

                    }
                    popupWindow.dismiss();
                }
                break;
        }
    }

    private void initPopupWindow() {
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_bag, null);
        popupWindow = new PopupWindow(v, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        //设置PopupWindow的属性
        ColorDrawable dw = new ColorDrawable(0xb0000000);//设置背景色
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.getBackground().setAlpha(50);//设置透明度
        popupWindow.setOutsideTouchable(true);//设置可以点击
        popupWindow.setFocusable(true);//使popupwindow获得焦点
        popupWindow.setTouchable(true);

        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
//        popupWindow.showAtLocation(v, Gravity.BOTTOM,0,0);

        //初始化Popupwindow上的控件
        tv_sum = (TextView) v.findViewById(R.id.pop_bag_sum);
        pop_bag_price = (TextView) v.findViewById(R.id.pop_bag_price);
        pop_bag_text = (TextView) v.findViewById(R.id.pop_bag_text);

        btn_plus = (ImageButton) v.findViewById(R.id.pop_bag_plus);
        btn_minus = (ImageButton) v.findViewById(R.id.pop_bag_minus);
        btn_sure = (Button) v.findViewById(R.id.btn_pop_sure);

        tv_sum.setOnClickListener(this);
        btn_minus.setOnClickListener(this);
        btn_plus.setOnClickListener(this);
        btn_sure.setOnClickListener(this);
    }

    //判断是否有重复数据
    private Boolean isRepeatedData() {
        String bag_text = (String) pop_bag_text.getText();
        for (int i = 0; i < MyApplication.laundries.size(); i++) {
            laundry = MyApplication.laundries.get(i);
            if (bag_text.equals(laundry.getPictureName())) {
                return true;
            }
        }
        return false;
    }
}
